package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**
     * 定义socket监听的端口号
     */
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private Mapper mapper = new Mapper();


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        //加载server.xml文件
        loadContext();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );





        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        /*while(true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/


        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();

        }*/


        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

            socket.close();

        }
*/

        /*
            多线程改造（不使用线程池）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/


//        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        /*while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, mapper);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }*/


        /**
         * 完成Minicat v4.0版本
         * 需求：添加Mapper组件，并支持多Context
         */
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, mapper);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }

    }

    private void loadContext() {
        InputStream resourceAsStream = this.getClass()
                                           .getClassLoader()
                                           .getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            //获取server标签
            Element rootElement = document.getRootElement();
            //获取service标签
            Element serviceElement = (Element) rootElement.selectSingleNode("Service");
            //获取Connector标签
            Element connectorElement = (Element) serviceElement.selectSingleNode("Connector");
            String port = connectorElement.attributeValue("port");
            //设置监听端口
            this.setPort(Integer.valueOf(port));
            //解析容器
            //获取Engine
            Element engineElement = (Element) serviceElement.selectSingleNode("Engine");
            //获取Host
            Element hostElement = (Element) engineElement.selectSingleNode("Host");
            StandardHost standardHost = new StandardHost();
            standardHost.setAppBase(hostElement.attributeValue("appBase"));
            standardHost.setName(hostElement.attributeValue("name"));
            Mapper.MappedHost mappedHost = new Mapper.MappedHost(standardHost.getName(), standardHost);
            //获取Context列表
            List<Element> contextElementList = hostElement.selectNodes("//Context");
            Mapper.MappedContext[] contexts = new Mapper.MappedContext[contextElementList.size()];
            Mapper.ContextList contextList = new Mapper.ContextList(contexts);
            for (int i = 0; i < contextElementList.size(); i++) {
                StandardContext standardContext = new StandardContext();
                standardContext.setDocBase(contextElementList.get(i)
                                                             .attributeValue("docBase"));
                standardContext.setPath(contextElementList.get(i)
                                                          .attributeValue("path"));
                Mapper.MappedContext mappedContext = new Mapper.MappedContext(standardContext.getPath(), standardContext);
                //加载appBase下的项目

                Wrapper[] wrappers = this.loadServlet(standardHost.getAppBase(), standardContext.getDocBase());
                //构造wrapper
                Mapper.MappedWrapper[] mappedWrappers = this.buildWrapper(wrappers);
                mappedContext.wrappers = mappedWrappers;
                contexts[i] = mappedContext;

            }
            mappedHost.setContextList(contextList);
            mapper.hosts = new Mapper.MappedHost[]{mappedHost};
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    private Mapper.MappedWrapper[] buildWrapper(Wrapper[] wrappers) {
        Mapper.MappedWrapper[] mappedWrappers = new Mapper.MappedWrapper[wrappers.length];
        for (int i = 0; i < wrappers.length; i++) {
            Mapper.MappedWrapper mappedWrapper = new Mapper.MappedWrapper(wrappers[i].getMappping(), wrappers[i]);
            mappedWrappers[i] = mappedWrapper;
        }
        return mappedWrappers;
    }


//    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();

    /**
     * 加载解析web.xml，初始化Servlet
     */
//    private void loadServlet() {
//        InputStream resourceAsStream = this.getClass()
//                                           .getClassLoader()
//                                           .getResourceAsStream("web.xml");
//        SAXReader saxReader = new SAXReader();
//
//        try {
//            Document document = saxReader.read(resourceAsStream);
//            Element rootElement = document.getRootElement();
//
//            List<Element> selectNodes = rootElement.selectNodes("//servlet");
//            for (int i = 0; i < selectNodes.size(); i++) {
//                Element element = selectNodes.get(i);
//                // <servlet-name>lagou</servlet-name>
//                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
//                String servletName = servletnameElement.getStringValue();
//                // <servlet-class>server.LagouServlet</servlet-class>
//                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
//                String servletClass = servletclassElement.getStringValue();
//
//
//                // 根据servlet-name的值找到url-pattern
//                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
//                // /lagou
//                String urlPattern = servletMapping.selectSingleNode("url-pattern")
//                                                  .getStringValue();
//                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass)
//                                                              .newInstance());
//
//            }
//
//
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//
//    }
    private Wrapper[] loadServlet(String appBase, String docBase) {
        SAXReader saxReader = new SAXReader();
        Wrapper[] wrappers = new Wrapper[0];
        try {
            Document document = saxReader.read(new File(appBase + "/" + docBase + "/" + "web.xml"));
            Element rootElement = document.getRootElement();

            List<Element> servletElementList = rootElement.selectNodes("//servlet");
            wrappers = new Wrapper[servletElementList.size()];
            for (int i = 0; i < servletElementList.size(); i++) {
                Element element = servletElementList.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern")
                                                  .getStringValue();

                StandardWrapper standardWrapper = new StandardWrapper(urlPattern, servletClass);
                wrappers[i] = standardWrapper;
            }


        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException("加载servlet异常");
        }
        return wrappers;
    }



    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
